<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sa="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>文章管理</title>
    <link rel="stylesheet" th:href="@{/pear/component/pear/css/pear.css}"/>
</head>
<body class="pear-container">
<div class="layui-card">
    <div class="layui-card-body">
        <form class="layui-form" action="">
            <div class="layui-form-item">
                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">文章标题</label>
                    <div class="layui-input-inline">
                        <input type="text" name="title" placeholder="请输入文章标题" class="layui-input" id="title">
                    </div>
                </div>

                <div class="layui-form-item layui-inline">
                    <button class="layui-btn layui-btn-sm  " lay-submit lay-filter="article-query">
                        <i class="layui-icon layui-icon-search"></i>
                        查询
                    </button>
                    <button type="reset" class="layui-btn layui-btn-sm" id="resetBtn">
                        <i class="layui-icon layui-icon-refresh"></i>
                        重置
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="layui-card">
    <div class="layui-card-body">
        <table id="article-table" lay-filter="article-table"></table>
    </div>
</div>

<script type="text/html" id="article-toolbar">
    <button class="layui-btn   layui-btn-sm" lay-event="add" sa:hasPermission="infoArticle_add">
        <i class="layui-icon layui-icon-add-1"></i>
        新增
    </button>
    <button class="layui-btn layui-btn-danger layui-btn-sm" lay-event="batchRemove"
            sa:hasPermission="infoArticle_delete">
        <i class="layui-icon layui-icon-delete"></i>
        删除
    </button>
</script>

<script type="text/html" id="article-bar">
    <button class="layui-btn layui-bg-blue layui-btn-sm" sa:hasPermission="infoArticle_list" lay-event="view"><i
            class="layui-icon layui-icon-eye"></i>
    </button>
    <button class="layui-btn  layui-btn-sm" sa:hasPermission="infoArticle_update" lay-event="edit"><i
            class="layui-icon layui-icon-edit"></i>
    </button>
    <button class="layui-btn layui-btn-danger layui-btn-sm" sa:hasPermission="infoArticle_delete" lay-event="remove"><i
            class="layui-icon layui-icon-delete"></i>
    </button>
</script>

<script th:src="@{/pear/component/layui/layui.js}"></script>
<script th:src="@{/pear/component/pear/pear.js}"></script>
<script th:inline="javascript">

    layui.use(['table', 'form', 'jquery', 'util'], function () {
        let table = layui.table;
        let form = layui.form;
        let $ = layui.jquery;
        let util = layui.util;
        let baseURL = /*[[@{/}]]*/ '';
        //获取栏目id
        let queryString = window.location.search;
        // 解析查询参数
        let urlParams = new URLSearchParams(queryString);
        const channelId = urlParams.get('infoId');
        window.channelId = channelId

        let cols = [
            [
                {type: 'checkbox'},
                {field: 'title', title: '标题', minWidth: 200, align: "left"},
                {field: 'channelName', title: '来源（栏目名称）', align: "left"},
                {field: 'sort', title: '排序值', sort: true, align: "center"},
                {
                    field: 'status', title: '状态', minWidth: 120, sort: true, align: "center", templet: function (d) {
                        const statusMap = {
                            0: "待审核",
                            1: "待发布",
                            2: "已发布",
                            3: "被驳回"
                        };
                        let statusText = statusMap[d.status] || "error";
                        let s = '';
                        if (d.status === 3) {
                            s = '<span style="font-size: 10px;color: #01AAED;cursor: pointer;border-bottom: 1px solid #01AAED" class="reasons-name" data-id="' + d.reason + '">点击查看理由</span>'
                        }
                        return '<span>' + statusText + s + '</span>'
                    }
                },
                {field: 'count', title: '浏览量', sort: true, align: "center"},
                {field: 'articleTime', title: '发布时间', align: "center"},
                {title: '操作', templet: '#article-bar', width: 240, align: 'center'}
            ]
        ]
        table.render({
            elem: '#article-table',
            url: baseURL + 'cms/infoArticle/list',
            type: 'get',
            where: {
                channelId: channelId
            },
            toolbar: '#article-toolbar',
            page: true,
            limit: 10,
            limits: [10, 20, 30],
            request: {
                pageName: 'pageNum',
                limitName: 'pageSize'
            },
            parseData: function (res) {
                console.log(res.data.list)
                return {
                    "code": res.code,
                    "msg": res.msg,
                    "count": res.data.total,
                    "data": res.data.list.map(item => ({
                        ...item,
                        title: item.title,
                        author: item.author,
                        description: item.description,
                    }))
                };
            },
            cols: cols,
            response: {
                statusCode: 1000
            }
        });
        // 监听查询按钮，动态加载表格数据
        form.on('submit(article-query)', function (data) {
            // 获取表单中的查询条件
            let field = data.field;

            // 重新加载表格，并传递查询参数
            table.reload('article-table', {
                where: {
                    channelId: channelId,
                    title: field.title,  // 栏目名查询条件
                },
                page: {
                    curr: 1 // 从第一页开始
                }
            });

            return false; // 阻止表单跳转
        });

        table.on('tool(article-table)', function (obj) {
            if (obj.event === 'remove') {
                window.remove(obj);
            } else if (obj.event === 'edit') {
                window.edit(obj);
            } else if (obj.event === 'view') {
                window.view(obj);
            }
        });

        table.on('toolbar(article-table)', function (obj) {
            if (obj.event === 'add') {
                window.add(obj);
            } else if (obj.event === 'batchRemove') {
                window.batchRemove(obj);
            }
        });


        $(document).on('click', '.reasons-name', function () {
            let reason = $(this).data('id');
            layer.alert(reason);
        });

        //打开新增文章页面
        window.add = function (obj) {
            let loading = layer.load();
            $.ajax({
                url: baseURL + 'cms/channel/getTemplateCode',
                type: 'GET',
                data: {channelId: window.channelId},
                success: function (data) {
                    layer.close(loading);
                    if (data.code === 1000) {
                        let id = obj.config.id;
                        let getData = table.getData(id);
                        if (getData.length > 0 && data.data.code === "ARTICLE") {
                            showErrorMessage("一篇文章类型模板下只能有一篇文章！");
                            return
                        }
                        if (data.data.code === "LINK") {
                            openLinkAddPage();
                            return
                        }
                        openArticleAddPage();  // 请求成功时打开文章新增页面
                    } else {
                        showErrorMessage(data.msg);  // 请求失败时显示错误信息
                    }
                },
                error: function () {
                    layer.close(loading);
                    showErrorMessage('请求失败，请稍后再试');  // 网络错误时显示统一的错误信息
                }
            });
        };

        // 打开文章新增页面的函数
        function openArticleAddPage() {
            layer.open({
                type: 2,
                title: '新增文章',
                shade: 0.1,
                area: ['100%', '100%'],
                content: 'article_add' // 更新为你的新增页面路径
            });
        }

        // 打开文章新增页面的函数
        function openLinkAddPage() {
            layer.open({
                type: 2,
                title: '新增链接',
                shade: 0.1,
                area: ['100%', '100%'],
                content: 'article_link_add' // 更新为你的新增页面路径
            });
        }

        // 显示错误信息的函数
        function showErrorMessage(message) {
            layer.msg(message, {
                icon: 2,
            });
        }

        //打开文章的编辑页面，并传值
        window.edit = function (obj) {
            window.articleId = obj.data.articleId;
            if (obj.data.status === 1 || obj.data.status === 2) {
                showErrorMessage("文章已发布，不能修改")
                return
            }
            if (obj.data.channelId !== Number(window.channelId)) {
                showErrorMessage("被推送的文章无法修改！");
                return
            }
            window.articleId = obj.data.articleId
            let loading = layer.load();
            $.ajax({
                url: baseURL + 'cms/channel/getTemplateCode',
                type: 'GET',
                data: {channelId: window.channelId},
                success: function (data) {
                    layer.close(loading);
                    if (data.code === 1000) {
                        let channelIdName = data.data.channelName
                        let channelIdId = data.data.channelId

                        window.channelNames = obj.data.channelNames.split(",").map(String).filter(num => num !== channelIdName).join(",")
                        window.channelIds = obj.data.channels.split(",").map(Number).filter(num => num !== channelIdId)
                        if (data.data.code === "LINK") {
                            window.state = obj.data.status
                            window.publishedTime = obj.data.publishedTime
                            layer.open({
                                type: 2,
                                title: '链接修改',
                                shade: 0.1,
                                shadeClose: true,
                                area: ['100%', '100%'],
                                content: 'article_link_edit',
                                success: function (layero, index) {
                                    // 数据回显
                                    let body = layer.getChildFrame('body', index)
                                    let data = obj.data;
                                    body.find("input[name=title]").val(data.title)
                                    body.find("input[name=sort]").val(data.sort)
                                    body.find("textarea[name=description]").val(data.description)
                                    body.find("input[name=articleTime]").val(data.articleTime)


                                }
                            })
                            return
                        }
                        $.ajax({
                            url: baseURL + 'cms/infoArticle/getContentById',
                            type: 'get',
                            data: {articleId: window.articleId},
                            success: function (data) {
                                layer.close(loading);
                                const decodedData = atob(data.data.content);
                                window.content = new TextDecoder('utf-8').decode(new Uint8Array([...decodedData].map(char => char.charCodeAt(0))));
                                window.contentId = data.data.contentId
                                window.state = obj.data.status
                                window.publishedTime = obj.data.publishedTime
                                layer.open({
                                    type: 2,
                                    title: '文章修改',
                                    shade: 0.1,
                                    shadeClose: true,
                                    area: ['100%', '100%'],
                                    content: 'article_edit',
                                    success: function (layero, index) {
                                        // 数据回显
                                        let body = layer.getChildFrame('body', index)
                                        let data = obj.data;
                                        console.log(data)
                                        body.find("input[name=title]").val(data.title)
                                        body.find("input[name=author]").val(data.author)
                                        body.find("input[name=sort]").val(data.sort)
                                        body.find("textarea[name=description]").val(data.description)
                                        body.find("#ID-upload-demo-img").attr('src', baseURL + data.resourceUrl)
                                        body.find("input[name=resourceUrl]").val(data.resourceUrl)
                                        body.find("input[name=articleTime]").val(data.articleTime)
                                        //动态显示输入框的字数限制
                                        let maxLengthTitle = body.find('#articleTitle').attr('maxlength');
                                        let currentLengthTitle = data.title.length;
                                        body.find('#titleCharCount').text(currentLengthTitle + "/" + maxLengthTitle);
                                        let maxLengthDesc = body.find('#articleDescription').attr('maxlength');
                                        let currentLengthDesc = data.description.length;
                                        body.find('#descCharCount').text(currentLengthDesc + "/" + maxLengthDesc);
                                        if (data.attachmentUrl !== "" && data.attachmentUrl !== null) {
                                            window.attachmentUrl = data.attachmentUrl
                                            const fileName = data.attachmentUrl.split('/').pop().split('_').slice(1).join('_');
                                            // 显示文件名和图标
                                            body.find('#file_p').html(
                                                `${fileName}
                                        <a href="${baseURL}${data.attachmentUrl}" download="${fileName}" style="margin-left: 10px; color: #1e9fff;">
                                        点击下载查看附件
                                        </a>`
                                            );
                                            body.find('#removeAttachment').show();
                                            body.find("input[name=attachmentUrl]").val(data.attachmentUrl)
                                        }

                                    }
                                })
                            },
                            error: function () {
                                layer.close(loading);
                                showErrorMessage('请求失败，请稍后再试');
                            }
                        })
                    } else {
                        showErrorMessage(data.msg);  // 请求失败时显示错误信息
                    }
                },
                error: function () {
                    layer.close(loading);
                    showErrorMessage('请求失败，请稍后再试');  // 网络错误时显示统一的错误信息
                }
            });

        }

        //删除文章
        window.remove = function (obj) {
            if (obj.data.channelId !== Number(window.channelId)) {
                showErrorMessage("被推送的文章无法修改！");
                return
            }
            if (obj.data.status === 1 || obj.data.status === 2) {
                showErrorMessage("文章已发布，不能删除")
                return
            }
            layer.confirm("确定要删除该文章吗", {icon: 3, title: '提示'}, function (index) {
                layer.close(index);
                let loading = layer.load();
                $.ajax({
                    url: baseURL + "cms/infoArticle/delete/" + obj.data['articleId'],
                    dataType: 'json',
                    type: 'post',
                    success: function (result) {
                        layer.close(loading);
                        if (result.code === 1000) {
                            layer.msg(result.msg, {
                                icon: 1,
                                time: 2000
                            }, function () {
                                window.tableReload()
                            });
                        } else {
                            showErrorMessage(result.msg)
                        }
                    },
                    error: function () {
                        layer.close(loading);
                        showErrorMessage('请求失败，请稍后再试');
                    }
                });
            });
        };
        //批量删除文章
        window.batchRemove = function (obj) {
            let data = table.checkStatus(obj.config.id).data;
            if (data.length === 0) {
                layer.msg("未选中数据", {icon: 3, time: 2000});
                return false;
            }
            let hasStatus1Or2 = data.some(item => item.status === 1 || item.status === 2);
            if (hasStatus1Or2) {
                showErrorMessage("文章已发布，不能删除")
                return
            }
            let hasPush = data.some(item => item.channelId !== Number(window.channelId));
            if (hasPush) {
                showErrorMessage("被推送的文章无法删除")
                return
            }
            let ids = data.map(item => item.articleId)

            layer.confirm('确定要删除选中的文章吗？', {icon: 3, title: '提示'}, function (index) {
                layer.close(index);
                let loading = layer.load();
                $.ajax({
                    url: baseURL + "cms/infoArticle/removeBatch",
                    data: {
                        articleIds: ids
                    },
                    dataType: 'json',
                    type: 'post',
                    success: function (result) {
                        layer.close(loading);
                        if (result.code === 1000) {
                            layer.msg(result.msg, {icon: 1, time: 2000}, function () {
                                window.tableReload();
                            });
                        } else {
                            showErrorMessage(result.msg)
                        }
                    },
                    error: function () {
                        layer.close(loading);
                        showErrorMessage('请求失败，请稍后再试');
                    }
                });
            });
        };

        let cachedChannelUrl = null; // 用于缓存 channelUrl

        function getChannelUrl(channelId) {
            return new Promise((resolve, reject) => {
                if (cachedChannelUrl) {
                    // 如果已经缓存，直接返回
                    resolve(cachedChannelUrl);
                } else {
                    // 未缓存时发起请求
                    $.ajax({
                        url: baseURL + 'cms/channel/getChannelUrlById',
                        type: 'get',
                        data: {channelId: channelId},
                        success: function (data) {
                            cachedChannelUrl = data.data; // 缓存结果
                            resolve(cachedChannelUrl);
                        },
                        fail: function () {
                            reject("服务器错误");
                        }
                    });
                }
            });
        }

        window.view = function (obj) {
            getChannelUrl(channelId)
                .then(channelUrl => {
                    let loading = layer.load();
                    $.ajax({
                        url: baseURL + 'cms/channel/getTemplateCode',
                        type: 'GET',
                        data: {channelId: window.channelId},
                        success: function (data) {
                            layer.close(loading);
                            if (data.code === 1000) {
                                if (data.data.code === 'ARTICLE' || data.data.code === "LINK") {
                                    channelUrl = "cms/column/" + channelUrl
                                } else if (data.data.code === 'LIST') {
                                    channelUrl = "cms/info/" + channelUrl + '/' + obj.data.articleId
                                }
                                util.openWin({
                                    url: 'article_view_check' + '?channelUrl=' + channelUrl + '&articleId=' + obj.data.articleId + '&isChecked=' + data.data.isChecked,
                                });
                            } else {
                                showErrorMessage(data.msg)
                            }
                        },
                        error: function () {
                            layer.close(loading);
                            showErrorMessage("服务器错误")
                        }
                    })
                })
                .catch(error => {
                    showErrorMessage("服务器错误")
                });
        };


        //重置按钮
        document.getElementById('resetBtn').addEventListener('click', function () {
            window.tableReload()
        });

        //刷新表格
        window.tableReload = function () {
            table.reload('article-table', {
                where: {
                    channelId: channelId
                }, page: {curr: 1}
            });
        }

        $.ajax({
            url: baseURL + "setting/getSettingValue",
            type: 'get',
            data: {
                settingKey: "ARTICLE_RESOURCE"
            },
            success: function (res) {
                window.resourceSize = parseInt(res.data, 10)
            }
        })

        $.ajax({
            url: baseURL + "setting/getSettingValue",
            type: 'get',
            data: {
                settingKey: "ARTICLE_ATTACHMENT"
            },
            success: function (res) {
                window.attachmentSize = parseInt(res.data, 10)
            }
        })

    })


</script>
</body>
</html>
